package com.stockz.equity.charting.view;

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.stockz.equity.charting.decorator.StockChartPanelLayoutDecorator;
import com.stockz.equity.charting.event.EventPublisher;
import com.stockz.equity.charting.event.SetStockChartViewPortEvent;
import com.stockz.equity.charting.event.StockChartPanelFirstTimePaintEvent;
import com.stockz.equity.charting.painter.StockChartPanelPainter;

@Component
@Scope("prototype")
public class StockChartPanel extends JPanel{
	private static final long serialVersionUID = 3723244455190418620L;
	
	private static boolean firstTimePaint = true;
	
	private final StockChartPanelState stockChartPanelState;
	private final StockChartPanelSkin stockChartPanelSkin;
	private final StockChartPanelStructure stockChartPanelStructure;
	private final StockChartPanelPainter stockChartPanelPainter;
	private final StockChartPanelLayoutDecorator stockChartPanelLayoutDecorator;
	private StockChart stockChart;
	
	
	@Autowired
	public StockChartPanel(StockChartPanelState stockChartPanelState,
			StockChartPanelPainter stockChartPanelPainter,
			StockChartPanelLayoutDecorator stockChartPanelLayoutDecorator,
			StockChartPanelSkin stockChartPanelSkin,
			StockChartPanelStructure stockChartPanelStructure){
		this.stockChartPanelState = stockChartPanelState;
		this.stockChartPanelSkin = stockChartPanelSkin;
		this.stockChartPanelStructure = stockChartPanelStructure;
		this.stockChartPanelPainter = stockChartPanelPainter;
		this.stockChartPanelLayoutDecorator = stockChartPanelLayoutDecorator;
		setBorder(null);
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if(firstTimePaint){
			EventPublisher.publishEvent(new StockChartPanelFirstTimePaintEvent(this));
		}
		if(stockChart == null){
			return;
		}
		stockChartPanelLayoutDecorator.decorate(stockChart);
		stockChartPanelPainter.paint((Graphics2D)g, stockChart, getVisibleRect());
		if(firstTimePaint){
			EventPublisher.publishEvent(new SetStockChartViewPortEvent(stockChart));
			firstTimePaint = false;
		}
	}
	
	@Override
	protected void paintBorder(Graphics g) {
	}
	
	public StockChartPanelSkin getStockChartPanelSkin() {
		return stockChartPanelSkin;
	}

	public StockChartPanelStructure getStockChartPanelStructure() {
		return stockChartPanelStructure;
	}

	public StockChart getStockChartView() {
		return stockChart;
	}

	public void setStockChart(StockChart stockChartView) {
		this.stockChart = stockChartView;
	}

	public StockChartPanelState getStockChartPanelState() {
		return stockChartPanelState;
	}
}
